package org.ithasu.tools.net.http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

import org.ithasu.tools.Console;
import org.ithasu.tools.IOTools;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HTTPTools {

	public static HttpServer create(int port) {
		try {
			return HttpServer.create(new InetSocketAddress(port), 0);
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	// -- HTTP ----------------------------------------

	public static String getWebPage(String url) {
		try {
			URL addr = new URL(url);
			URLConnection c = addr.openConnection();
			return new String(IOTools.read(c.getInputStream()));
		} catch (Exception e) {
			Console.error(e);
			return null;
		}
	}

	// -- Contexts ----------------------------------------

	public static HttpContext registerContext(HttpServer server, String url, HttpHandler handler) {
		if (server == null) {
			Console.error(new NullPointerException());
			return null;
		} else {
			try {
				HttpContext context = server.createContext(url, handler);
				return context;
			} catch (Exception e) {
				Console.error(e);
				return null;
			}
		}
	}

	public static HttpContext registerExitContext(final HttpServer server, String url) {
		return registerContext(server, url, new HttpHandler() {
			@Override
			public void handle(HttpExchange t) throws IOException {
				server.stop(1);
				writeResponse_HTML(t, 200, "<html><title>Server status</title><body><b>Exited</b></body></html>");
			}
		});
	}

	// -- Response ----------------------------------------

	public static void writeResponse_redirect(HttpExchange t, String url) {
		try {
			writeResponse_HTML(t, 200, "<html><head><meta http-equiv=\"Refresh\" content=\"0; url=" + url
					+ "\"/></head><body><a href=\"" + url + "\">You are being redirected</a></body></html>");
		} catch (Exception e) {
			Console.error(e);
		}
	}

	public static void writeResponse_HTML(HttpExchange t, int status, String html) {
		writeResponse(t, status, "text/html", html.getBytes());
	}

	public static void writeResponse(HttpExchange t, int status, String contentType, byte[] data) {
		try {
			t.getResponseHeaders().put("Content-Type", Arrays.asList(contentType));
			t.sendResponseHeaders(status, data == null ? 0 : data.length);
			if (data != null) {
				t.getResponseBody().write(data);
			}
			t.close();
		} catch (Exception e) {
			Console.error(e);
		}
	}

}
